<?php namespace App\Controllers\Manager;

//http://www.codeforest.net/laravel4-simple-website-with-backend-1
 
use App\Models\Page;
use App\Models\PageTemplate;
use App\Models\PageRow;
use App\Models\PageBlock;
use Input, Redirect, Sentry, Str;
use Notification;
 
class PagesController extends \BaseController {
 
    public function index()
    {
        return \View::make('manager.pages.index')
            ->with('pages', Page::all())
            ->with('pagelist', $this->getStructuredList(0));
    }
 
    public function show($id)
    {
        return \View::make('manager.pages.show')
            ->with('page', Page::find($id));
    }
 
    public function create()
    {
        $page_templates = array();
        foreach(PageTemplate::all() as $page_template)
        {
            $page_templates[$page_template->id] = $page_template->title;
        }

        return \View::make('manager.pages.create')
            ->with('page_templates', $page_templates);
    }
 
    public function store()
    {
        $page = new Page;
        $page->parentid   = Input::get('parentid',0);
        $page->pagetemplateid   = Input::get('pagetemplateid',1);
        $page->is_homepage   = Input::get('is_homepage',false);
        $page->pageorder = (Page::getMaxPageOrder()) + 1;
        $page->name   = Input::get('name');
        $page->slug    = Str::slug(Input::get('slug'));
        $page->title   = Input::get('title');
        $page->description   = Input::get('description');
        $page->keywords   = Input::get('keywords');
        $page->content    = Input::get('content', '');
        $page->status = Input::get('status');
        $page->save();

	    $page->rows()->delete();
		$page_content = json_decode(Input::get("page_content"));

	    if(isset($page_content->rows))
	    {
		    for($i=0; $i < count($page_content->rows); $i++)
		    {
			    $row = new PageRow();
			    $row->displayorder = $i;
			    $row->save();

			    for($j=0; $j < count($page_content->rows[$i]->blocks); $j++)
			    {
				    $block = new PageBlock();
				    $block->span = $page_content->rows[$i]->blocks[$j]->span;
				    $block->offset = $page_content->rows[$i]->blocks[$j]->offset;
				    $block->content = $page_content->rows[$i]->blocks[$j]->content;
				    $block->displayorder = $j;
				    $block->save();
				    $row->blocks()->save($block);
			    }

			    $page->rows()->save($row);
		    }
	    }

        Notification::success('The page was saved.');
     
        return Redirect::route('manager.pages.index');
    }
 
    public function edit($id)
    {
        $page_templates = array();
        foreach(PageTemplate::all() as $page_template)
        {
            $page_templates[$page_template->id] = $page_template->title;
        }

        return \View::make('manager.pages.edit')
            ->with('page', Page::find($id))
            ->with('page_templates', $page_templates)
	        ->with('paqe_content', $this->getPageContent($id));
    }
 
    public function update($id)
    {
        $page = Page::find($id);
        $page->parentid   = Input::get('parentid',0);
        $page->pagetemplateid   = Input::get('pagetemplateid',1);
        //$page->is_homepage   = Input::get('is_homepage',false);
        //$page->pageorder = (Page::getMaxPageOrder()) + 1;
        $page->name   = Input::get('name');
        //$page->slug    = Str::slug(Input::get('title'));
        $page->title   = Input::get('title');
        $page->slug   = Str::slug(Input::get('slug'));
        $page->description   = Input::get('description');
        $page->keywords   = Input::get('keywords');
        $page->content    = Input::get('content');
        $page->status = Input::get('status');
        $page->save();

	    foreach($page->rows()->get() as $row)
	    {
		    $row->blocks()->delete();
	    }
	    $page->rows()->delete();

	    $page_content = json_decode(Input::get("page_content"));

	    if(isset($page_content->rows))
	    {
		    for($i=0; $i < count($page_content->rows); $i++)
		    {
			    $row = new PageRow();
			    $row->displayorder = $i;
			    $row->save();

			    for($j=0; $j < count($page_content->rows[$i]->blocks); $j++)
			    {
				    $block = new PageBlock();
				    $block->span = $page_content->rows[$i]->blocks[$j]->span;
				    $block->offset = $page_content->rows[$i]->blocks[$j]->offset;
				    $block->content = $page_content->rows[$i]->blocks[$j]->content;
				    $block->displayorder = $j;
				    $block->save();
				    $row->blocks()->save($block);
			    }

			    $page->rows()->save($row);
		    }
	    }

        Notification::success('The page was saved.');
     
        return Redirect::route('manager.pages.edit', $page->id);
    }
 
    public function destroy($id)
    {
        $page = Page::find($id);
        $page->delete();

        Notification::info('The page was deleted.');

        return Redirect::route('manager.pages.index');
    }

    public function move()
    {
        $parentid = Input::get("parentid", 0);
        $children = Input::get("children", array());

        if(count($children) > 0)
        {
            foreach($children as $order=>$child)
            {
                $page = Page::find($child);
                $page->parentid   = $parentid;
                $page->pageorder = $order + 1;
                $page->save();
            }
        }
        
        return \Response::json(array("message" => "Moved!", "parentid" => $parentid, "children" => $children));
    }

	public function makeHomepage($pageid)
	{
		\DB::table("pages")
			->update(["is_homepage"=>0]);

		\DB::table("pages")
			->where("id", $pageid)
			->update(["is_homepage"=>1]);

		Notification::success('Homepage updated!');

		return Redirect::route('manager.pages.index');
	}

    public function getQuickEdit($id)
    {
        $page_templates = array();
        foreach(PageTemplate::all() as $page_template)
        {
            $page_templates[$page_template->id] = $page_template->title;
        }
        return \View::make('manager.pages.quickedit')
            ->with('page', Page::find($id))
            ->with('page_templates', $page_templates);
    }

    public function getSlug()
    {
        return \Response::json(array(
            "val" => Str::slug(Input::get("str"))
        ));
    }
    
    public function saveQuickEdit()
    {
        $page = Page::find(Input::get("pageid"));
        $page->pagetemplateid   = Input::get('pagetemplateid',1);
        $page->name   = Input::get('name');
        $page->title   = Input::get('title');
        $page->description   = Input::get('description');
        $page->keywords   = Input::get('keywords');
		$page->status = Input::get('status');
        $page->save();
        

        return \Response::json(array(
            "message" => "Updated!", 
            "id" => Input::get("pageid"),
            "name" => Input::get('name'), 
            "title" => Input::get('title'),
            "is_homepage" => Input::get('pagetemplateid',1)
        ));
    }

    // Utility Functions
    public function getStructuredList($parentid=0, $class="blocklist", $id="pagelist")
    {
        $html = "<ul class='$class' id='$id-$parentid'>";

        $subs = Page::where("parentid", $parentid)->orderby("pageorder")->get();

        foreach ($subs as $child) {
            $current_id = $child->id;
            $html .= "<li data-pageid='$current_id'><div class='blocklistitem'>";
            if($child->is_homepage)
            {
                $html .= "<i class='fa fa-fw fa-home'></i>";
            }

	        if($child->status == 0)
	        {
		        $html .= "<span style='text-decoration:line-through; color:#D43F3A;'>{$child->name}</span>";
	        }
	        else
	        {
		        $html .= "{$child->name}";
	        }



            $html .= "<a href='". \URL::route("manager.pages.edit", $current_id) . "' class='btn btn-xxs quick-edit pull-right' data-pageid='{$current_id}' data-showing='false' data-toggle='tooltip' title='Quick Edit'><i class='fa fa-fw fa-edit'></i></a>";
            if(!$child->is_homepage)
            {
	            $html .= "<a class='btn btn-info btn-xxs pull-right' href='/manager/pages/makehomepage/$current_id' data-toggle='tooltip' title='Make Homepage'><i class='fa fa-fw fa-home'></i></a>";
	            $html .= \Form::open(array(
                    "route" => array("manager.pages.destroy", $current_id), 
                    "method" => "delete",
                    "class" => "pull-right delete-page"
                ));
                    $html .= "<button class='btn btn-danger btn-xxs' type='submit' data-toggle='tooltip' title='Delete'><i class='fa fa-fw fa-trash-o'></i></button>";

                $html .= \Form::close();
            }
            $html .= "<a href='". \URL::route("manager.pages.edit", $current_id) . "' class='btn btn-xxs btn-warning pull-right' data-toggle='tooltip' title='Edit'><i class='fa fa-fw fa-edit'></i></a>";
            $html .= "</div>";
            
            if(Page::where("parentid", $current_id)->count() > 0)
            {
                $html .= $this->getStructuredList($current_id, $class, $id);
            }
            
            $html .= "</li>";
        }
        $html .= "</ul>";
        return $html;
    }

	public function getPageContent($pageid)
	{
		$page = Page::find($pageid);

		$page_content = array("rows" => array());

		$rows = $page->rows()->orderBy("displayorder")->get();

		foreach($rows as $row)
		{
			$temp_row = array("blocks"=>array());

			$blocks = $row->blocks()->orderBy("displayorder")->get();

			foreach($blocks as $block)
			{
				$temp_block = array();
				$temp_block["span"] = $block->span;
				$temp_block["offset"] = $block->offset;
				$temp_block["content"] = $block->content;

				array_push($temp_row["blocks"], $temp_block);
			}

			array_push($page_content["rows"], $temp_row);
		}

		return json_encode($page_content);

	}
}